package com.example.bingobox.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.bingobox.R;
import com.example.bingobox.model.Task;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class TaskSelectionAdapter extends RecyclerView.Adapter<TaskSelectionAdapter.ViewHolder> {
    private List<Task> tasks;
    private Set<String> selectedTaskIds = new HashSet<>();

    public TaskSelectionAdapter(List<Task> tasks) {
        this.tasks = tasks;
    }

    // 添加这个方法来设置任务的选中状态
    public void setTaskSelected(String taskId, boolean selected) {
        if (selected) {
            selectedTaskIds.add(taskId);
        } else {
            selectedTaskIds.remove(taskId);
        }
        notifyDataSetChanged();
    }

    // 获取选中的任务列表
    public List<Task> getSelectedTasks() {
        return tasks.stream()
                .filter(task -> selectedTaskIds.contains(task.getId()))
                .collect(Collectors.toList());
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_task_selection, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Task task = tasks.get(position);
        holder.checkBox.setText(task.getName());
        holder.checkBox.setChecked(selectedTaskIds.contains(task.getId()));
        holder.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                selectedTaskIds.add(task.getId());
            } else {
                selectedTaskIds.remove(task.getId());
            }
        });
    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        CheckBox checkBox;

        ViewHolder(View view) {
            super(view);
            checkBox = view.findViewById(R.id.checkbox_task);
        }
    }
} 